import {getEnv, getQuery} from './util'
import { Toast } from 'vant';
export default ({
  pageTitle, //页面title
  shareImg, //分享图
  title, //标题
  secondTitle, //副标题
  ifMini, //分享给好友时是否为小程序
  shareTo, //分享到 [0 ,1]: [微信好友, 朋友圈]
  shareAddress,  //分享地址，不传则为当前页面地址（小程序会拼接登录字段）
  miniAddress //分享的小程序地址（不传则默认生成）
}) => {
  if (shareTo.length) {
    let imgAddress = shareImg;
    let isCBD = navigator.userAgent.indexOf('chebada') != -1;
    let isWX =
      navigator.userAgent.toLowerCase().match(/MicroMessenger/i) ==
      'micromessenger';
    if (isCBD) {
      let webPageUrl = location.href;
      if (webPageUrl.indexOf('?') === -1) webPageUrl += '?';
      let miniWebPageUrl = shareAddress || `${webPageUrl}&isskey=1&refresh=1`;
      // const webPageUrl = `${location.origin}${location.pathname}?recordId=${recordId}&isskey=1&refresh=1`
      const path = miniAddress || `pages/web/web?url=${encodeURIComponent(
        miniWebPageUrl,
      )}&isSocket=true`;
      setTimeout(() => {
        if (!ifMini) {
          let shareparam = {
            title: pageTitle,
            shareTitle: title,
            shareContent: secondTitle,
            shareTypes: shareTo,
            shareImg: imgAddress,
            shareUrl: shareAddress || window.location.href,
          };
          cbdztUtil.setPageTitle(shareparam);
        } else {
          let titleParam = {
            title: pageTitle,
            rightMenuConfig: {
              type: 'shareParams',
              shareParams: { paramList: [] },
            },
            "backKeyCallback":function(){
              bridge.naviPlugins.closePage()
              // if(window.location.hash == ""){
              //   bridge.naviPlugins.closePage()
              // }else{
              //   window.history.back()
              // }
            },
          };
          let paramList = [];
          if (shareTo.includes(0)) {
            paramList.push({
              shareTo: '1',
              title: title,
              summary: '',
              // shareContent: secondTitle,
              contentType: '8',
              shareUrl: '',
              thumbnail: imgAddress,
              miniProgram: {
                webPageUrl: miniWebPageUrl,
                userName: 'gh_0aacaec14151',
                path: path,
              },
            });
          }
          if (shareTo.includes(1)) {
            paramList.push({
              shareTo: '2',
              contentType: '1',
              title: title,
              shareContent: secondTitle,
              shareUrl: miniWebPageUrl,
              thumbnail: imgAddress,
            });
          }
          titleParam.rightMenuConfig.shareParams.paramList = paramList;
          bridge.naviPlugins.setNaviTitle(titleParam);
        }
      }, 600);
    }
    if (isWX) {
      wx.miniProgram.getEnv(function (res) {
        if (res.miniprogram) {
          wx.miniProgram.postMessage({
            data: {
              title: title,
              shareUrl:  shareAddress|| window.location.href,
              imageUrl: imgAddress,
            },
          });
        } else {
          var shareInfo = {
            shareTitle: title,
            shareDesc: secondTitle,
            shareImage: imgAddress,
            shareUrl: shareAddress || window.location.href,
          };
          var shareUtil = cbdztUtil.cbdShareUtil(shareInfo);
          //微信二次分享
          shareUtil.wxTwiceShare();
          //qq分享
          shareUtil.qqShare();
        }
      });
    }
  }
}


// 手动分享
// app分享
const activityShare = async params => {
  const { title, shareUrl, shareImg, path, imgUrl } = params;
  const shareParams = {
    paramList: [
      {
        shareTo: "1",
        title,
        shareUrl: shareUrl,
        miniProgram: {
          webPageUrl: shareUrl,
          userName: "gh_0aacaec14151",
          path
        },
        contentType: "8",
        thumbnail: shareImg,
        summary: ""
      }
    ]
  };
  try {
    bridge.utilsPlugins.startShare(shareParams);
  } catch (e) {
    bridge.utilsPlugins.toast("您还未安装微信");
  }
}; 
let MyCorrespond = null;
export const initCorrespond = (uuid) => {
  let query = getQuery()
  MyCorrespond = new Correspond({
    systemId: "chebada.com",
    groupName: "webview",
    notify: false,
    userId: uuid || query.uuid, //取url里 uuid参数值
  });
}
//获取用户昵称
export const getUserProfile = () => {
  return new Promise((resolve, reject) => {
    MyCorrespond.getUserProfile((data) => {
      if(data.feedback)resolve(data.userInfo)
      else reject('获取失败')
    }, (data) => {
      reject(data)
    })
  })
}
export const subscription = (params) => {
  MyCorrespond.requestSubscribeMessage(params)
}
//手动分享（到小程序）
//小程序中使用之前需初始化correspond，使用上面的initCorrespond方法
export const startShare = async ({
  title,
  shareUrl,
  shareImg,
  path, //小程序地址
}) => {
  let env = await getEnv();
  if(env === 'cbd'){
    activityShare({
      title,
      shareUrl,
      shareImg,
      path,
    });
  }else if(env === 'mini'){
    if(MyCorrespond){
      MyCorrespond.share({
        shareInfo: {
          currentPath: shareUrl,
          title,
          imageUrl:shareImg,
          path: path,
        },
        shareVisible: true,
      });
    }else{
      Toast('初始化分享失败');
    }
  }else{
    Toast('当前无法分享');
  }
}